﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using MixScriptWeb.Share;
using MixScript.BLL;
using MixScriptWeb.control;
using MixScript.BLL.FI;
using MixScript.BLL.Accounting;
using System.Xml;
using System.Globalization;

namespace MixScriptWeb.Accounting
{
    public partial class fJournalCash : cCommonWeb2, IMIxCommon
    {
        public static DataTable dtMain = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                LoadData(Convert.ToInt32(Request.QueryString["editID"]));
                txtDetAmm.Attributes.Add("onKeyUp", "javascript:GetConvert();");
                txtDetRate.Attributes.Add("onKeyUp", "javascript:GetConvert();");
                ddlDetailDC_selectedChange(null, null);
            }
        }
        private void LoadData(int editID)
        {
            txtDate.Text = String.Format("{0:dd-MM-yyyy}", DateTime.Now);
            if (Request.QueryString["type"] == "2")
            {
                Page.Title = "Cash Receivable";
                lblTitle.Text = "Cash Receivable";
                txtFirstNo.Text = "CR" + txtDate.Text.Split('-')[1];
                lblDC.Text = "Debit";
                ddlDetailDC.SelectedIndex = 1;
            }
            else
            {
                Page.Title = "Cash Payable";
                lblTitle.Text = "Cash Payable";
                txtFirstNo.Text = "CP" + txtDate.Text.Split('-')[1];
                lblDC.Text = "Credit";
                ddlDetailDC.SelectedIndex = 0;

            }
            cAccHeader gj = new cAccHeader();
            txtSecondNo.Text = gj.getMaxJournalNo(txtFirstNo.Text, DateTime.Now.Year);

            DataTable dt = new DataTable();

            FillDropDownList(ddlBank, "mst_bank", "bankname", "banknum", true);
            FillDropDownList(ddlCurrency, "mst_currency", "currency", "currency", true);
            FillDropDownList(ddlDetailCurrency, "mst_currency", "currency", "currency", true);
            FillDropDownList(ddlCashCurrency, "mst_currency", "currency", "currency", true);

            cReferences oref = new cReferences();
            if (oref.getComboboxdata("accaccounts", "acctnum +'-'+ acctname  acctname", "acctnum", "", ref dt))
            {
                ddlDetailAccountNo.DataTextField = "acctname";
                ddlDetailAccountNo.DataValueField = "acctnum";
                ddlDetailAccountNo.DataSource = dt;
                ddlDetailAccountNo.DataBind();
            }


            cJournal jrnl = new cJournal();
            DataSet ds = new DataSet();
            ds = jrnl.CreateTable(Session["userid"].ToString(), editID);
            dtMain = ds.Tables[0];
            if (editID != 0)
            {
                DataTable dtHeader = new DataTable();
                dtHeader = ds.Tables[1];
                txtDate.Text = ((DateTime)dtHeader.Rows[0].ItemArray[2]).ToString("dd-MM-yyyy");
                txtDescription.Text = dtHeader.Rows[0].ItemArray[7].ToString();
                txtFirstNo.Text = dtHeader.Rows[0].ItemArray[4].ToString();
                txtSecondNo.Text = dtHeader.Rows[0].ItemArray[5].ToString();
                txtDescription.Text = dtHeader.Rows[0].ItemArray[7].ToString();
            }
            else
            {
                gj = new cAccHeader();
                txtDate.Text = DateTime.Now.ToString("dd-MM-yyy");
            }
            if (dtMain.Rows.Count > 0)
            {
                gvdetail.DataSource = dtMain;
                gvdetail.DataBind();
            }
            else
            {
                GlobalFunction funct = new GlobalFunction();
                dtMain = funct.InizializeColumn();
                funct.ShowNoResultFound(dtMain, gvdetail);
            }

            dt = new DataTable();
            cAccHeader acc = new cAccHeader();
            acc.getAccByProcess(out dt, rblType.SelectedValue.ToString());
            ddlCashAccount.DataSource = dt;
            ddlCashAccount.DataTextField = "acctname";
            ddlCashAccount.DataValueField = "acctnum";
            ddlCashAccount.DataBind();


            ddlCashCurrency_indexChange(null, null);
            ddlDetailCurrency_indexChange(null, null);

        }
        protected void ddlCashCurrency_indexChange(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            cCurrency cur = new cCurrency();

            cur.GetCurrency(out dt, txtDate.Text.Split('-')[2], txtDate.Text.Split('-')[1], ddlCashCurrency.SelectedItem.Value);
            if (dt.Rows.Count == 0)
                txtDetRate.Text = "1";
            else
            {  //rate , jual , beli
                if (ddlCashKurs.SelectedIndex == 0)
                    txtCashRate.Text = dt.Rows[0].ItemArray[2].ToString();
                else if (ddlCashKurs.SelectedIndex == 1)
                    txtCashRate.Text = dt.Rows[0].ItemArray[3].ToString();
                else if (ddlCashKurs.SelectedIndex == 2)
                    txtCashRate.Text = dt.Rows[0].ItemArray[4].ToString();
                else
                    txtCashRate.Text = "1";
            }

        }
        protected void ddlDetailCurrency_indexChange(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            cCurrency cur = new cCurrency();

            cur.GetCurrency(out dt, txtDate.Text.Split('-')[2], txtDate.Text.Split('-')[1], ddlDetailCurrency.SelectedItem.Value);
            if (dt.Rows.Count == 0)
                txtDetRate.Text = "1";
            else
            {  //rate , jual , beli
                if (ddlDetailKurs.SelectedIndex == 0)
                {
                    txtDetRate.Text = dt.Rows[0].ItemArray[2].ToString().Split('.')[0].ToString();
                    hfDetRate.Value = dt.Rows[0].ItemArray[2].ToString().Split('.')[0].ToString();
                }
                else if (ddlDetailKurs.SelectedIndex == 1)
                {
                    txtDetRate.Text = dt.Rows[0].ItemArray[3].ToString().Split('.')[0].ToString();
                    hfDetRate.Value = dt.Rows[0].ItemArray[3].ToString().Split('.')[0].ToString();
                }
                else if (ddlDetailKurs.SelectedIndex == 2)
                {
                    txtDetRate.Text = dt.Rows[0].ItemArray[4].ToString().Split('.')[0].ToString();
                    hfDetRate.Value = dt.Rows[0].ItemArray[4].ToString().Split('.')[0].ToString();
                }
                else
                    txtDetRate.Text = "1";
            }

        }
        public bool isvalid()
        {
            if (txtDescription.Text == string.Empty)
            {
                //mn = (MainMenu)this.Master;
                //ShowStatusBar("Header description cannot be empty");
                return false;
            }
            return true;
        }

        protected void gvdetail_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                txtSumDebet.Text = "0";
                txtSumKredit.Text = "0";
                txtSumTotal.Text = "0";
                txtCashCredit.Text = "0";
            }
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                double debit, credit, total;
                double.TryParse(e.Row.Cells[7].Text, out debit);
                double.TryParse(e.Row.Cells[8].Text, out credit);

                if (Request.QueryString["type"] == "2")
                {
                    txtSumKredit.Text = (credit + Convert.ToDouble(txtSumKredit.Text)).ToString("c").Replace("$", "");
                    txtCashCredit.Text = txtSumKredit.Text;
                    txtSumDebet.Text = txtCashCredit.Text;
                    txtCashConvert.Text = (Convert.ToDecimal(txtCashCredit.Text.ToString()) * Convert.ToDecimal(txtCashRate.Text.ToString())).ToString();
                }
                else
                {
                    txtSumDebet.Text = (debit + Convert.ToDouble(txtSumDebet.Text)).ToString("c").Replace("$", "");
                    txtCashCredit.Text = txtSumDebet.Text;
                    txtSumKredit.Text = txtCashCredit.Text;
                    txtCashConvert.Text = (Convert.ToDecimal(txtCashCredit.Text.ToString()) * Convert.ToDecimal(txtCashRate.Text.ToString())).ToString();
                }
                total = (Convert.ToDouble(txtSumDebet.Text)) - (Convert.ToDouble(txtSumKredit.Text));
                txtSumTotal.Text = total.ToString("c").Replace("$", "");
            }
        }
        protected void gvdetail_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Edited")
            {
                cJournal jrnl = new cJournal();
                ViewState["ID"] = Convert.ToInt32(e.CommandArgument);
                DataTable dt = jrnl.GetSub(Session["userid"].ToString(), Convert.ToInt32(e.CommandArgument));
                clear(false);
                ddlDetailAccountNo.SelectedItem.Value = dt.Rows[0].ItemArray[2].ToString();
                ddlDetailAccountNo_indexChange(null, null);
                txtDetailDescription.Text = dt.Rows[0].ItemArray[3].ToString();
                txtDetAmm.Text = dt.Rows[0].ItemArray[9].ToString();
                txtDetConvert.Text = dt.Rows[0].ItemArray[10].ToString();
                ddlDetailDC.SelectedItem.Value = dt.Rows[0].ItemArray[4].ToString();
                ddlDetailCurrency.SelectedItem.Value = dt.Rows[0].ItemArray[5].ToString();
                ddlDetailKurs.SelectedItem.Value = dt.Rows[0].ItemArray[6].ToString();
                txtDetRate.Text = dt.Rows[0].ItemArray[7].ToString();
                txtDetailInvoice.Text = dt.Rows[0].ItemArray[12].ToString();
                txtDetailTerms.Text = dt.Rows[0].ItemArray[17].ToString();
                if (dt.Rows[0].ItemArray[19].ToString() != "")
                {
                    string dateInv = ((DateTime)dt.Rows[0].ItemArray[19]).ToString("dd-MM-yyyy");
                    txtDetailDate.Text = dateInv;
                }
                if (dt.Rows[0].ItemArray[14].ToString().Trim() != "")
                {
                    ddlSubsidiaryNo.SelectedItem.Value = dt.Rows[0].ItemArray[14].ToString();
                    ddlSubsidiaryNo.Enabled = true;
                }
                else
                {
                    ddlSubsidiaryNo.Enabled = false;
                }

            }
            else if (e.CommandName == "Deleting")
            {
                cJournal jrnl = new cJournal();
                jrnl.Delete(Session["userid"].ToString(), Convert.ToInt32(e.CommandArgument));
                dtMain = jrnl.GetSubAll(Session["userid"].ToString());
                gvdetail.DataSource = dtMain;
                gvdetail.DataBind();
            }

        }
        protected void ddlDetailAccountNo_indexChange(object sender, EventArgs e)
        {

            DataTable dt = new DataTable();
            cAccSubLedger gj = new cAccSubLedger();
            if (gj.getSubsidiary(ref dt, (string)ddlDetailAccountNo.SelectedItem.Value)) ;
            {

                if (dt.Rows.Count > 0)
                {
                    ddlSubsidiaryNo.DataTextField = "name";
                    ddlSubsidiaryNo.DataValueField = "no";
                    ddlSubsidiaryNo.Enabled = true;
                    ddlSubsidiaryNo.DataSource = dt;
                    ddlSubsidiaryNo.DataBind();
                }
                else
                {
                    ddlSubsidiaryNo.Items.Clear();
                    ddlSubsidiaryNo.DataSource = null;
                    ddlSubsidiaryNo.DataBind();
                    ddlSubsidiaryNo.Enabled = false;

                }
            }
            String subID = "";
            if (ddlSubsidiaryNo.SelectedItem != null)
                subID = ddlSubsidiaryNo.SelectedItem.Value.ToString();
            pnlInvoiceSel.Style["display"] = "none";
            pnlInvoiceText.Style["display"] = "block";
            dt = new DataTable();
            cReferences oref = new cReferences();
            ddlInvoice.Items.Clear();
            if (gj.getAcc(out dt, (string)ddlDetailAccountNo.SelectedItem.Value))
            {
                if (dt.Rows[0].ItemArray[7].ToString() == "4")
                {
                    if (ddlDetailDC.SelectedItem.Value == "C")
                    {
                        pnlInvoiceSel.Style["display"] = "block";
                        pnlInvoiceText.Style["display"] = "none";
                        if (oref.getComboboxdata(" tb_dnmst mst inner join tb_invdtl det On  mst.delno=det.delno ", "invno", "invno", "cuid='" + subID + "'", ref dt))
                        {
                            ddlInvoice.DataTextField = "invno";
                            ddlInvoice.DataValueField = "invno";
                            ddlInvoice.DataSource = dt;
                            ddlInvoice.DataBind();
                        }
                    }

                }
                else if (dt.Rows[0].ItemArray[7].ToString() == "7")
                {
                    if (ddlDetailDC.SelectedItem.Value == "C")
                    {
                        pnlInvoiceSel.Style["display"] = "block";
                        pnlInvoiceText.Style["display"] = "none";
                        if (oref.getComboboxdata("tb_pomst", "pono", "pono", "codfbpid='" + subID + "'", ref dt))
                        {
                            ddlInvoice.DataTextField = "pono";
                            ddlInvoice.DataValueField = "pono";
                            ddlInvoice.DataSource = dt;
                            ddlInvoice.DataBind();
                        }
                    }
                }
            }

        }
        protected void ddlDetailDC_selectedChange(Object sender, EventArgs e)
        {
            try
            {
                cReferences oref = new cReferences();
                cAccSubLedger gj = new cAccSubLedger();
                DataTable dt = new DataTable();
                pnlInvoiceSel.Style["display"] = "none";
                pnlInvoiceText.Style["display"] = "block";
                dt = new DataTable();
                ddlInvoice.Items.Clear();
                String subID = "";
                if (ddlSubsidiaryNo.SelectedItem != null)
                    subID = ddlSubsidiaryNo.SelectedItem.Value.ToString();
                if (gj.getAcc(out dt, (string)ddlDetailAccountNo.SelectedItem.Value))
                {
                    if (dt.Rows[0].ItemArray[7].ToString() == "4")
                    {
                        if (ddlDetailDC.SelectedItem.Value == "C")
                        {
                            pnlInvoiceSel.Style["display"] = "block";
                            pnlInvoiceText.Style["display"] = "none";
                            if (oref.getComboboxdata(" tb_dnmst mst inner join tb_invdtl det On  mst.delno=det.delno ", "invno", "invno", "cuid='" + subID + "'", ref dt))
                            {
                                ddlInvoice.DataTextField = "invno";
                                ddlInvoice.DataValueField = "invno";
                                ddlInvoice.DataSource = dt;
                                ddlInvoice.DataBind();
                            }
                        }
                    }
                    else if (dt.Rows[0].ItemArray[7].ToString() == "7")
                    {
                        if (ddlDetailDC.SelectedItem.Value == "C")
                        {
                            pnlInvoiceSel.Style["display"] = "block";
                            pnlInvoiceText.Style["display"] = "none";
                            if (oref.getComboboxdata("tb_pomst", "pono", "pono", "codfbpid='" + subID + "'", ref dt))
                            {
                                ddlInvoice.DataTextField = "pono";
                                ddlInvoice.DataValueField = "pono";
                                ddlInvoice.DataSource = dt;
                                ddlInvoice.DataBind();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            { }
        }
        protected void btnSave_click(object sender, EventArgs e)
        {
            try
            {
                if (ddlSubsidiaryNo.SelectedValue == "Please Select") { throw new Exception("Please Select Subsidiary First"); }
                {
                    string subsidiary = "";
                    if (ddlSubsidiaryNo.Enabled == true)
                        subsidiary = ddlSubsidiaryNo.SelectedItem.Value;
                    cJournal jrnl = new cJournal();
                    string dateInvoice = "";
                    if (txtDetailDate.Text.Trim() != "")
                        dateInvoice = txtDetailDate.Text.Split('-')[2] + "-" +
                            txtDetailDate.Text.Split('-')[1] + "-" + txtDetailDate.Text.Split('-')[0];
                    string dateInvoicePo = "";
                    if (txtPoInvoiceDate.Text.Trim() != "")
                        dateInvoicePo = txtPoInvoiceDate.Text.Split('-')[2] + "-" +
                            txtPoInvoiceDate.Text.Split('-')[1] + "-" + txtPoInvoiceDate.Text.Split('-')[0];
                    if (ViewState["ID"] != null)
                    {

                        jrnl.Delete(Session["userid"].ToString(), (Int32)ViewState["ID"]);
                        dtMain = jrnl.InsertSub((Int32)ViewState["ID"], "0", ddlDetailAccountNo.SelectedItem.Value, txtDetailDescription.Text,
                            ddlDetailDC.SelectedItem.Value, ddlCurrency.SelectedItem.Value, ddlDetailKurs.SelectedItem.Value,
                            hfDetRate.Value, txtDetAmm.Text, hfDetConvert.Value, txtDetailInvoice.Text, "0", subsidiary,
                            dateInvoice, txtDetailTerms.Text, txtPoInvice.Text, dateInvoicePo, Session["userid"].ToString());
                    }
                    else
                    {
                        dtMain = jrnl.InsertSub(dtMain.Rows.Count + 1, "0", ddlDetailAccountNo.SelectedItem.Value, txtDetailDescription.Text,
                                ddlDetailDC.SelectedItem.Value, ddlCurrency.SelectedItem.Value, ddlDetailKurs.SelectedItem.Value,
                                hfDetRate.Value, txtDetAmm.Text, hfDetConvert.Value, txtDetailInvoice.Text, "0", subsidiary,
                                dateInvoice, txtDetailTerms.Text, txtPoInvice.Text, dateInvoicePo, Session["userid"].ToString());
                    }

                    gvdetail.DataSource = dtMain;
                    gvdetail.DataBind();
                    //Session["journal"] = journals;
                    ViewState["ID"] = null;
                }
            }
            catch (Exception ex)
            {
                //Response.Write("<script type='javascript'> alert('" + ex.Message + "')</script>");
                //mn = (MainMenu)this.Master;
                //ShowStatusBar(ex.Message);
            }
            clear(false);

        }
        private void clear(bool All)
        {

            if (All)
            {
                txtFirstNo.Text = string.Empty;
                txtSecondNo.Text = string.Empty;
                txtSecondNo.Text = string.Empty;
                txtDescription.Text = string.Empty;
            }
            ddlDetailAccountNo.SelectedIndex = 0;
            ddlSubsidiaryNo.Items.Clear();
            txtDetAmm.Text = string.Empty;
            txtDetConvert.Text = string.Empty;
            txtDetailDate.Text = string.Empty;
            txtDetailDescription.Text = string.Empty;
            txtDetailInvoice.Text = string.Empty;
            txtDetailTerms.Text = string.Empty;


        }
        protected void btnSaveAll_click(object sender, EventArgs e)
        {
            if (isvalid())
            {
                int editid = 0;
                if (Request.QueryString["editID"] != null)
                    editid = Convert.ToInt32(Request.QueryString["editID"]);
                int id;
                cJournal jrnl = new cJournal();
                id = jrnl.Save(editid, txtFirstNo.Text, txtSecondNo.Text, ddlCurrency.SelectedItem.Value,
                    txtDescription.Text, Convert.ToDateTime(txtDate.Text.Split('-')[2] + "-" + txtDate.Text.Split('-')[1] + "-" + txtDate.Text.Split('-')[0]),
                    Session["userid"].ToString());
                string dc = "c";
                if (Request.QueryString["editID"] == "3")
                    dc = "d";

                jrnl.InsertSubPembanding(id, ddlCashAccount.SelectedItem.Value, txtCashDescripiton.Text, dc, ddlCashCurrency.SelectedItem.Value,
                    ddlCashKurs.SelectedItem.Value, txtCashRate.Text, txtCashCredit.Text.Replace(",", ""), txtCashConvert.Text, "", "0", "", "", "", "", "");



                Response.Redirect("ListJournal.aspx?type=" + (String)Request.QueryString["type"]);
            }
        }
        protected void btnReset_click(object sender, EventArgs e)
        {
            clear(true);
        }
        protected void rblType_selectedIndex(Object sender, EventArgs e)
        {
            if (rblType.SelectedValue.ToString() == "2")
            {
                pnlType.Style["display"] = "none";
                if (Request.QueryString["type"] == "2")
                    txtFirstNo.Text = "CR" + txtDate.Text.Split('-')[1];
                else
                    txtFirstNo.Text = "CP" + txtDate.Text.Split('-')[1];

            }
            else
            {
                pnlType.Style["display"] = "block";
                if (Request.QueryString["type"] == "2")
                    txtFirstNo.Text = "BR" + txtDate.Text.Split('-')[1];
                else
                    txtFirstNo.Text = "BP" + txtDate.Text.Split('-')[1];

            }
            DataTable dt = new DataTable();
            cAccHeader acc = new cAccHeader();
            acc.getAccByProcess(out dt, rblType.SelectedValue.ToString());
            ddlCashAccount.DataSource = dt;
            ddlCashAccount.DataTextField = "acctname";
            ddlCashAccount.DataValueField = "acctnum";
            ddlCashAccount.DataBind();

        }

    }
}